package com.black.play.listener.key;

import lombok.Getter;
import lombok.Setter;

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * @author ylx
 */
@Getter
@Setter
public abstract class KeyCodeAdapter<T extends Component> extends KeyAdapter {

    protected boolean isPreventDefault;
    protected T component;

    public KeyCodeAdapter(T component) {
        this(component, false);
    }

    public KeyCodeAdapter(T component, boolean isPreventDefault) {
        this.isPreventDefault = isPreventDefault;
        this.component = component;
    }

    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (isPreventDefault && keyCode == targetKeyCode()) {
            e.consume();
        }
        keyPressed(keyCode);
    }

    public void keyPressed(int keyCode) {
        if (keyCode == targetKeyCode()) {
            keyPressed();
        }
    }

    public abstract void keyPressed();

    public abstract int targetKeyCode();
}
